/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年11月27日         Root.Lu
 */

package com.coocaa.x.framework.app;

import com.coocaa.x.framework.utils.LiteHandlerThread;
import com.coocaa.x.framework.utils.LogUtils;

public abstract class Container {
    private LiteHandlerThread lht = null;
    private String name = null;

    private boolean bCreated = false, bDestroyed = false;

    public Container(String name) {
        this.name = name;
    }

    public final void create() {
        synchronized (Container.this) {
            if (lht == null) {
                lht = new LiteHandlerThread("HandlerThread(" + name + ")");
                lht.start();
                postAction(new Runnable() {
                    @Override
                    public void run() {
                        long st = System.currentTimeMillis();
                        onCreate();
                        LogUtils.d(lht.getName() + " onCreate cost:"
                                + (System.currentTimeMillis() - st));
                        bCreated = true;
                    }
                });
            }
        }
    }

    public final void destroy() {
        synchronized (Container.this) {
            if (lht != null) {
                postAction(new Runnable() {
                    @Override
                    public void run() {
                        onDestroy();
                        synchronized (Container.this) {
                            lht.quit();
                            lht = null;
                        }
                        bCreated = false;
                        bDestroyed = true;
                    }
                });
            }
        }
    }

    public final String getName() {
        return name;
    }

    public final boolean isCreated() {
        return bCreated;
    }

    public final boolean isDestroyed() {
        return bDestroyed;
    }

    public final void postAction(Runnable run) {
        postAction(run, 0);
    }

    public final void postAction(Runnable run, long delay) {
        synchronized (Container.this) {
            if (lht != null)
                lht.postDelayed(run, delay);
        }
    }

    // public final void clearAction(Runnable run)
    // {
    // ht.clearAction(run);
    // }

    protected void uncaughtException(Thread t, Throwable e) {
        e.printStackTrace();
    }

    protected abstract void onCreate();

    protected abstract void onDestroy();
}
